import { defineStore } from 'pinia';
import { UserInfosState, UserLocalInfosState } from './interface';
import { reactive } from 'vue';
import { Local } from '/@/utils/storage';
// import { ElMessage } from 'element-plus';
import { TeListener } from '/@/utils/eListener';
// import { formatAxis } from '../utils/formatTime';
// import { getUserInfoByToken } from '../api/user';
export const userIdPwd = 'dj87857*djdj87857*wsdj'
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', () => {
	let userInfos = reactive({
		userInfos: {
			photo: '',
			userName: '',
			logintime: '',
			token: '',
			id: 0,
			loginProgramName: '',
			loginPhone: '',
			roles: [],
			perIds: []
		} as UserInfosState,
		userLocalInfos: {
			oldPhones: []
		} as UserLocalInfosState,
		authBtnList: [] as any[],
		commonMuneList: [] as { id: string, count: number, path: string, title: string }[],
		state: {
			roomName: ''
		}
	})
	// let isCheckToken = false
	let isTokenOk = false

	interface PermissionMgr {
		isObjNew?: boolean
	}
	const perMgr = reactive<PermissionMgr>({})

	const onChange = new TeListener()

	initSet()
	return {
		userInfos, perMgr, setCheckToken, saveUserInfo, getIsToken,
		getToken, getPhone, getRoles, clear, getUid,
		checkTokenActive, exitLogin, IsAdmin, setCheckLoginSuccess,
		updateUserData, getPhoto, onChange, setRoom, getPerIds, getTokenActived, saveAddCommonMuneList
	}

	function initSet() {
		if (Local.get('userInfo')) {
			userInfos = Local.get('userInfo');
		}
		if (!userInfos.commonMuneList || userInfos.commonMuneList.length < 6) {
			userInfos.commonMuneList = []
			save()
		}
	}
	// 存储用户信息到浏览器缓存
	function save() {
		Local.set('userInfo', userInfos);
		onChange.fire()
	}

	function IsAdmin() {
		return userInfos.userInfos.isAdmin
	}

	function getIsToken() {
		return true // userInfos.userInfos.token || (isCheckToken && isTokenOk)
	}
	function getToken() {
		return userInfos.userInfos.token
	}

	function getPhone() {
		return userInfos.userInfos.loginPhone
	}

	function getPhoto() {
		return userInfos.userInfos.photo
	}

	function getUid() {
		return userInfos.userInfos.id
	}

	function getRoles() {
		return userInfos.userInfos.roles || []
	}

	function getPerIds() {
		return userInfos.userInfos.perIds || []
	}

	function updateUserData(userName?: string, photo?: string) {
		if (userName !== undefined) {
			userInfos.userInfos.userName = userName
		}
		if (photo !== undefined) {
			userInfos.userInfos.photo = photo
		}
		save()
	}

	function saveUserInfo(userInfo: UserInfosState) {
		userInfos.userInfos = userInfo
		save()
	}

	function setRoom(roomName: string) {
		userInfos.state.roomName = roomName
		save()
	}

	function saveAddCommonMuneList(id: string, path: string, title: string) {
		let muneObj = userInfos.commonMuneList.forof(a => a.id === id)
		if (!muneObj) {
			muneObj = { id: id, count: 0, path: path, title: title }
			userInfos.commonMuneList.push(muneObj)
		}
		muneObj.count += 1
		userInfos.commonMuneList.sort((a, b) => a.count < b.count ? 1 : -1)
		save()
	}

	function clear() {
		userInfos.userInfos = {
			photo: '',
			userName: '',
			logintime: '',
			token: '',
			id: 0,
			loginProgramName: '',
			loginPhone: '',
			roles: [],
			perIds: [],
		}
		userInfos.state = {
			roomName: ''
		}
		setCheckToken(false, false)
		save()

	}

	async function setCheckLoginSuccess() {
		setCheckToken(true, false)
		// await reSetPer()
	}

	function setCheckToken(_isCheckToken = true, _isTokenOk = true) {
		// isCheckToken = _isCheckToken
		isTokenOk = _isTokenOk
	}

	function exitLogin() {
		userInfos.userInfos.token = ''
		userInfos.userInfos.pwd = ''
		userInfos.userInfos.isUidLogined = false
		setCheckToken(false, false)
		save()
	}

	function getTokenActived() {
		return !!getToken() && isTokenOk
	}
	async function checkTokenActive(_params?: any) {
		return true
		if (!getToken()) return false
		if (!isTokenOk) await getUserInfo()
		return isTokenOk
	}

	async function getUserInfo() {
		return
		// const res = await getUserInfoByToken()
		// const rd = res?.data as any
		// if (rd?.code === 0) {
		// 	isTokenOk = true
		// 	const rdt = rd.tdata
		// 	const userInfo = userInfos.userInfos
		// 	userInfo.userName = rdt.name
		// 	userInfo.photo = rdt.photo
		// 	userInfo.id = rdt.userId
		// 	const menuList = (rdt.role?.joinMenu || '') as string
		// 	userInfo.perIds = menuList ? menuList.split(',') : []//.slice(0, 20)
		// 	if (!userInfo.perIds.length) {
		// 		ElMessage.info('无任何权限！');
		// 		exitLogin()
		// 	} else {
		// 		ElMessage.success(`${formatAxis(new Date())}，${'欢迎回来！'}`);
		// 		save()
		// 	}
		// } else {
		// 	// ElMessage.warning(rd?.message || '请重新登录！');
		// }
	}
	// async function reSetPer() {
	// 	const perIds = userInfos.userInfos.perIds || []
	// 	while (!useRoutesList().getRoutesList().length) {
	// 		await window.awaitTime(50)
	// 	}
	// 	const menuLists = useRoutesList().getRoutesList()
	// 	for (const rr0 of menuLists) {
	// 		setPer(rr0.meta)
	// 		for (const rr1 of (rr0.children || [])) {
	// 			// if (!rr1.meta?.isCtrl) continue
	// 			setPer(rr1.meta)
	// 			for (const rr2 of (rr1.children || [])) {
	// 				setPer(rr2.meta)
	// 			}
	// 		}
	// 	}
}, {
	// //作为第三个参数配置
	// persist: {
	// 	enabled: true,
	// 	strategies: [{
	// 		paths: ['loadNum'], key: 'loadNum', storage: localStorage
	// 	}]
	// }
});